package com.ophiux.utils.parser.json;

import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonUtils {

	private JsonUtils() {
	}

	private static JsonUtils istance;

	public static void main(String[] args) {
		try {
			Integer.parseInt("sss");
		} catch (Exception e) {
		}
	}

	public static JsonUtils getIstance() {
		return (istance == null) ? (istance = new JsonUtils()) : istance;
	}

	protected static Logger logger = LoggerFactory.getLogger(JsonUtils.class);

	private final static Gson _gson = new GsonBuilder().serializeNulls().create();

	/**
	 * Json数据转为实体类
	 * @param json
	 * @param callback
	 * @return
	 */
	public static <T> T toEntity(String json, TypeObtainCallback callback) {
		T t = null;
		Type typeOfT = null;
		try {
			typeOfT = callback.getObtainType();
			t = _gson.fromJson(json, typeOfT);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("json解析错误，json = {" + json + "}，class = {},Exception = {}\n", typeOfT, e);
		}
		return t;
	}

	public <T> T toEntity(String json, Type type) {
		T t = null;
		Type typeOfT = type;
		try {
			t = _gson.fromJson(json, typeOfT);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("json解析错误，json = {" + json + "}，class = {},Exception = {}\n", typeOfT, e);
		}
		return t;

	}

	public <T> T toEntity(String json, Class<T> classOfT) {
		T t = null;
		try {
//			logger.info("传入的json===" + json);
			t = _gson.fromJson(json, classOfT);
		} catch (Exception e) {
			logger.error("解析json异常===" + json);
			e.printStackTrace();
//			logger.info("json解析错误，json = {" + json + "}，class = {},Exception = {}\n", toJson(e));
		}
		return t;
	}

	/**
	 * 转JSON
	 * @param data
	 * @return
	 */
	public static String toJson(Object data) {
		return _gson.toJson(data);
	}

	/**
	 * 获取请求参数类型回调
	 */
	public interface TypeObtainCallback {
		/**
		 * 获取参数类型，</br> 目前仅作用于官网服务请求返回参数Data字段类型
		 * @return
		 */
		public Type getObtainType();

	}
}
